//
//  ThemeManger.m
//  ThemeManager
//
//  Created by weiguang on 2017/1/13.
//  Copyright © 2017年 weiguang. All rights reserved.
//

#import "ThemeManger.h"

@implementation ThemeManger

+ (id)shareInstance {
    
    static dispatch_once_t once;
    static ThemeManger *obj = nil;
    dispatch_once(&once, ^{
        obj = [[ThemeManger alloc] init];
    });
    
    return obj;
}

- (id)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (void)setThemeColor:(UIColor *)color{
    //把当前颜色保存在本地，下次进入时保持该状态
    NSString *colorStr = [self toStrWithColor:color];
    [UserDefaults setObject:colorStr forKey:@"ThemeColor"];
}

- (UIColor *)getThemeColor{
    if ([UserDefaults objectForKey:@"ThemeColor"]) {
        UIColor *color = [self colorWithHexString:[UserDefaults objectForKey:@"ThemeColor"]];
        return color;
    }
    return RGBA(74, 125, 112, 1.0); //默认颜色
}

- (void)setThemeFont:(CGFloat)fontSize{
     [UserDefaults setFloat:fontSize forKey:@"ThemeFont"];
}

-(CGFloat)getThemeFont{
    if ([UserDefaults objectForKey:@"ThemeFont"]) {
        CGFloat size = [[UserDefaults objectForKey:@"ThemeFont"] floatValue];
        return size;
    }
    return 14;
}


- (UIColor *)colorWithHexString:(NSString *)color{
    //删除空格
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:(CGFloat) r / 255.0f
                           green:(CGFloat) g /255.0f
                            blue:(CGFloat) b /255.0f
                           alpha:1.0f];
}

//颜色 转字符串（16进制）
- (NSString *)toStrWithColor:(UIColor *)color{
    CGFloat r,g,b,a;
    [color getRed:&r green:&g blue:&b alpha:&a];
    int rgb = (int) (r * 255.0f)<<16 | (int) (g * 255.0f)<<8 | (int) (b * 255.0f)<<0;
    return [NSString stringWithFormat:@"%06x",rgb];
}


@end
